package com.goliathonline.android.kegbot;

import java.net.*;
import java.io.*;

import android.util.Log;


public class Connector
{
	private String _host;
	private int _port;
	private Socket _socket;
	private InputStream _inStream;
	private OutputStream _outStream;
	private InputStreamReader _inReader;
	private OutputStreamWriter _outWriter;
	private Util _util = new Util();
	
	public Connector(String host, int port)
	{
		_host = host;
		_port = port;
		OpenConnection();
	}
	
	private void OpenConnection()
	{
		try{
			_socket = new Socket(_host, _port);
			_inStream = _socket.getInputStream();
			_outStream = _socket.getOutputStream();
			_inReader = new InputStreamReader(_inStream);
			_outWriter = new OutputStreamWriter(_outStream);
			Log.d("Kegbot Connector","Connection Opened");
		}
		catch(Exception ex){
			Log.d("Kegbot Connector","Exception: " + ex.toString());
		}
	}
	
	public void SetHost(String host, int port)
	{
		_host = host;
		_port = port;
	}
	
	public boolean Connect()
	{
		if(!_socket.isConnected())
		{
			try{
				_socket = new Socket(_host, _port);
				_inStream = _socket.getInputStream();
				_outStream = _socket.getOutputStream();
				_inReader = new InputStreamReader(_inStream);
				_outWriter = new OutputStreamWriter(_outStream);
				return true;
			}
			catch(Exception ex){
				return false;
			}
		}
		return true;
	}
	
	public boolean Disconnect()
	{
		try {
			_socket.close();
		} catch (IOException e) {
			return true;
		}
		Log.d("Kegbot Connector","Disconnect socket");
		return _socket.isClosed();
	}
	
	public boolean IsConnected()
	{
		return _socket.isConnected();
	}
	public String Listen()
	{
		StringBuffer buffer = new StringBuffer();
		int ch;
		boolean posRead = false;
		if(_socket.isConnected())
		{
			Log.d("Kegbot Connector","Listening...");
			while(!posRead) 
			{
				try 
				{
					while(_inReader.ready())
					{
						ch = _inReader.read(); 
						buffer.append((char)ch);
						posRead = true;
					}
				}
				catch(Exception ex) {
					Log.d("Kegbot Connector","Listen error: " + ex.toString());
					return ex.toString();
				}
			}
			Log.d("Kegbot Connector","Received: " + buffer.toString());
			return buffer.toString();
		}
		Log.d("Kegbot Connector","Failed to listen");
		return "error";
	}
	
	public String TestConnection()
	{
		if(_socket.isConnected())
		{
			try {
				
				Kegnet.Ping.Builder pingBuild = Kegnet.Ping.newBuilder();
				Kegnet.Ping ping = pingBuild.build();
				_outWriter.write(_util.ProtoMessageToJson(ping) + "\n\n");
				_outWriter.flush();
				StringBuffer buffer = new StringBuffer();
				int ch;
				if(_inReader.ready())
					while ((ch = _inReader.read()) > -1) {
						buffer.append((char)ch);
					}
				return buffer.toString();
			}
			catch(Exception ex) {
				return ex.toString();
			}
		}
		else
			return "not connected";
	}
}
